#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.dev'

import django
django.setup()

import time, datetime
from random import randint
from django.db.models import Max

from orders.models import Express, OrderInfo, ExpressOrderRelevance, OrderProfitSharing, OrderAdvance, ExpressPlan, OrderAddress
from equity_mall.utils.utils import ryx_profitsharing_order
from merchants.models import MerchantBill
from equity_mall.utils.express_utils import KuaiDi100


def update_express_plan():
    print('%s: update_express_plan' % time.ctime())
    express_set = Express.objects.filter(deliverystatus__in=[0, 1, 5, 6, 2])
    for express in express_set:
        try:
            order = ExpressOrderRelevance.objects.filter(express_id=express.id).first()
            phone = OrderAddress.objects.filter(order_id=order.order_id).first()
            if phone:
                result = KuaiDi100().track(express.express_type.express_type, express.express_number, phone.mobile[-4:])
            else:
                result = KuaiDi100().track(express.express_type.express_type, express.express_number)
            if result['status'] == '200':
                express.deliverystatus = result['state']
                express.save()
                for i in result['data']:
                    plan_data = {}
                    plan_data['express_id'] = express.id
                    plan_data['create_time'] = i['time']
                    plan_data['remark'] = i['context']
                    ExpressPlan.objects.get_or_create(defaults=plan_data, create_time=i['time'], express_id=express.id)
                if str(express.deliverystatus) == "3":
                    try:
                        sign_time = ExpressPlan.objects.filter(express_id=express.id).aggregate(Max('create_time'))['create_time__max']
                        express.sign_time = sign_time
                        express.save()
                    except:
                        pass
            else:
                express.deliverystatus = 9
                express.save()
                ExpressPlan.objects.create(remark=result['message'], create_time=datetime.datetime.now(),express_id=express.id)
        except:
            print(f'{express.id}同步失败,{result}')


def sign_for_expired_order():
    print('%s: sign_for_expired_order' % time.ctime())
    today = datetime.datetime.now()
    last_week = today + datetime.timedelta(-29)
    sign_time__lte = last_week.strftime('%Y-%m-%d 23:59:59')
    sign_time__gte = last_week.strftime('%Y-%m-%d 00:00:00')
    order_set = OrderInfo.objects.exclude(state__in=[2, 8, 15]).filter(payment_time__gte=sign_time__gte, payment_time__lte=sign_time__lte, is_profit_sharing__in=[1, 3])
    for order in order_set:
        out_trade_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
        if order.is_profit_sharing == 1:
            body = {
                "program_id": "202316837141378884",
                "shop_id": order.merchant.ruiyinxinMerchantID,
                "order_id": out_trade_no,
                "out_trade_no": order.orderNum,
                "is_profit": "0"
            }
        else:
            body = {
                "program_id": "202316837141378884",
                "shop_id": order.merchant.ruiyinxinMerchantID,
                "order_id": out_trade_no,
                "out_trade_no": order.orderNum,
                "is_profit": "2"
            }
        result = ryx_profitsharing_order(body)
        profitorder = OrderProfitSharing.objects.filter(order_id=order.id).first()
        if not profitorder:
            profitorder, create = OrderProfitSharing.objects.get_or_create(defaults={'order_id': order.id, "out_trade_no": out_trade_no}, order_id=order.id)
        if result['result_code'] == 'success':
            order.is_profit_sharing = 2
            order.state = 14
            order.save()
            OrderAdvance.objects.create(
                order_id=order.id,
                status=4,
                remark='到期自动结算订单成功',
                user_id=1
            )
            profitorder.profit_order_id = result['profit_order_id']
            profitorder.profit_time = today
            profitorder.save()
            receipts_time = today.strftime('%Y-%m-%d')
            bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=order.merchant_id, bill_type=order.order_species).first()
            if not bill:
                bill_data = {}
                bill_data['merchant_id'] = order.merchant_id
                bill_data['receipts_time'] = receipts_time
                bill_data['amount'] = order.total_price
                bill_data['commission'] = order.freight
                bill_data['level_id'] = order.merchant.level_id
                bill_data['payable_amount'] = order.total_price - order.freight
                bill_data['channel_id'] = 3
                bill_data['bill_type'] = order.order_species
                bill, create = MerchantBill.objects.get_or_create(defaults=bill_data, receipts_time=receipts_time, merchant_id=order.merchant_id, bill_type=order.order_species)
            else:
                bill.amount = bill.amount + order.total_price
                bill.commission = bill.commission + order.freight
                bill.payable_amount = bill.payable_amount + order.total_price - order.freight
                bill.save()
            order.payable_settled_amount = order.total_price - order.freight
            order.bill_id = bill.id
            order.save()
            print(f'{order.id}解冻成功')
        else:
            if result['error_msg'] == '已超过分账有效时间，不允许发起分账':
                order.is_profit_sharing = 2
                order.state = 14
                order.save()
                OrderAdvance.objects.create(
                    order_id=order.id,
                    status=4,
                    remark='到期自动结算订单成功',
                    user_id=1
                )
                profitorder.profit_order_id = result['profit_order_id']
                profitorder.profit_time = datetime.datetime.now()
                profitorder.save()
                receipts_time = today.strftime('%Y-%m-%d')
                bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=order.merchant_id, bill_type=order.order_species).first()
                if not bill:
                    bill_data = {}
                    bill_data['merchant_id'] = order.merchant_id
                    bill_data['receipts_time'] = receipts_time
                    bill_data['amount'] = order.total_price
                    bill_data['commission'] = order.freight
                    bill_data['level_id'] = order.merchant.level_id
                    bill_data['payable_amount'] = order.total_price - order.freight
                    bill_data['channel_id'] = 3
                    bill_data['bill_type'] = order.order_species
                    bill, create = MerchantBill.objects.get_or_create(defaults=bill_data, receipts_time=receipts_time, merchant_id=order.merchant_id, bill_type=order.order_species)
                else:
                    bill.amount = bill.amount + order.total_price
                    bill.commission = bill.commission + order.freight
                    bill.payable_amount = bill.payable_amount + order.total_price - order.freight
                    bill.save()
                order.payable_settled_amount = order.total_price - order.freight
                order.bill_id = bill.id
                order.save()
                print(f'{order.id}解冻成功')
            else:
                order.is_profit_sharing = 2
                order.save()
                OrderAdvance.objects.create(
                    order_id=order.id,
                    status=4,
                    remark='到期自动结算订单失败',
                    user_id=1
                )
                profitorder.error_msg = result['error_msg']
                profitorder.profit_status = 2
                profitorder.save()
                print(f'{order.id}解冻失败')


def sign_for_order():
    print('%s: sign_for_order' % time.ctime())
    update_express_plan()
    today = datetime.datetime.now()
    last_week = today + datetime.timedelta(-7)
    sign_time__lte = last_week.strftime('%Y-%m-%d 23:59:59')
    sign_time__gte = last_week.strftime('%Y-%m-%d 00:00:00')
    express_set = Express.objects.filter(sign_time__lte=sign_time__lte, sign_time__gte=sign_time__gte).values_list('id', flat=True)
    if express_set:
        relevance_set = ExpressOrderRelevance.objects.filter(express_id__in=list(express_set)).values_list('order_id', flat=True)
        if relevance_set:
            for order_id in relevance_set:
                order = OrderInfo.objects.filter(state=6, is_profit_sharing__in=[1, 3], id=order_id, order_type=5).first()
                if order:
                    out_trade_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
                    if order.is_profit_sharing == 1:
                        body = {
                            "program_id": "202316837141378884",
                            "shop_id": order.merchant.ruiyinxinMerchantID,
                            "order_id": out_trade_no,
                            "out_trade_no": order.orderNum,
                            "is_profit": "0"
                        }
                    else:
                        body = {
                            "program_id": "202316837141378884",
                            "shop_id": order.merchant.ruiyinxinMerchantID,
                            "order_id": out_trade_no,
                            "out_trade_no": order.orderNum,
                            "is_profit": "2"
                        }
                    result = ryx_profitsharing_order(body)
                    profitorder = OrderProfitSharing.objects.filter(order_id=order.id).first()
                    if not profitorder:
                        profitorder, create = OrderProfitSharing.objects.get_or_create(defaults={'order_id': order.id, "out_trade_no": out_trade_no}, order_id=order.id)
                    if result['result_code'] == 'success':
                        order.is_profit_sharing = 2
                        order.state = 14
                        order.save()
                        OrderAdvance.objects.create(
                            order_id=order.id,
                            status=4,
                            remark='快递到期自动收货,结算订单成功',
                            user_id=1
                        )
                        profitorder.profit_order_id = result['profit_order_id']
                        profitorder.profit_time = datetime.datetime.now()
                        profitorder.save()
                        receipts_time = datetime.datetime.now().strftime('%Y-%m-%d')
                        bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=order.merchant_id, bill_type=order.order_species).first()
                        if not bill:
                            bill_data = {}
                            bill_data['merchant_id'] = order.merchant_id
                            bill_data['receipts_time'] = receipts_time
                            bill_data['amount'] = order.total_price
                            bill_data['commission'] = order.freight
                            bill_data['level_id'] = order.merchant.level_id
                            bill_data['payable_amount'] = order.total_price - order.freight
                            bill_data['channel_id'] = 3
                            bill_data['bill_type'] = order.order_species
                            bill, create = MerchantBill.objects.get_or_create(defaults=bill_data, receipts_time=receipts_time, merchant_id=order.merchant_id, bill_type=order.order_species)
                        else:
                            bill.amount = bill.amount + order.total_price
                            bill.commission = bill.commission + order.freight
                            bill.payable_amount = bill.payable_amount + order.total_price - order.freight
                            bill.save()
                        order.payable_settled_amount = order.total_price - order.freight
                        order.bill_id = bill.id
                        order.save()
                        print(f'{order_id}解冻成功')
                    else:
                        order.is_profit_sharing = 2
                        order.save()
                        OrderAdvance.objects.create(
                            order_id=order.id,
                            status=4,
                            remark='到期自动结算订单失败',
                            user_id=1
                        )
                        profitorder.error_msg = result['error_msg']
                        profitorder.profit_status = 2
                        profitorder.save()
                        print(f'{order_id}解冻失败')
    sign_for_expired_order()
    print(len(express_set))



if __name__ == '__main__':
    sign_for_expired_order()